import { setToken, getToken, removeToken } from '@/utils/token'
import { getMenuList } from '@/api/workbench'
import { handleMenuListRoutes, handleFirstRoute } from '@/utils'

export default {
  state: {
    navList: JSON.parse(localStorage.getItem('navList')) || [],
    currentNav: JSON.parse(localStorage.getItem('currentNav')) || '',
    menuList: JSON.parse(localStorage.getItem('menuList')) || [],
    // 用户信息
    userInfo: JSON.parse(localStorage.getItem('userInfo')) || {},
    token: getToken()
  },
  mutations: {
    SET_USERINFO(state, userInfo) {
      let { token } = userInfo
      setToken(token)
      localStorage.setItem('userInfo', JSON.stringify(userInfo))
      state.userInfo = userInfo
    },
    HANDLE_LOGOUT(state) {
      state.token = ''
      removeToken()
      state.userInfo = {}
      localStorage.removeItem('userInfo')
      state.navList = []
      localStorage.removeItem('navList')
      state.currentNav = ''
      localStorage.removeItem('currentNav')
      state.menuList = []
      localStorage.removeItem('menuList')
    },
    GET_NAVLIST(state, navList) {
      localStorage.setItem('navList', JSON.stringify(navList))
      state.navList = navList
    },
    GET_MENULIST(state, { menuList, currentNav }) {
      localStorage.setItem('currentNav', JSON.stringify(currentNav))
      localStorage.setItem('menuList', JSON.stringify(menuList))
      state.currentNav = currentNav
      state.menuList = menuList
    }
  },
  actions: {
    /**
     * 保存用户信息
     */
    SET_USERINFO({ commit }, userInfo) {
      commit('SET_USERINFO', userInfo)
    },
    /**
     * 处理退出
     */
    HANDLE_LOGOUT({ commit }) {
      commit('HANDLE_LOGOUT')
    },
    /**
     * 获取头部导航菜单
     */
    async GET_NAVLIST({ commit, state }) {
      return new Promise(async (resolve, reject) => {
        let { roleId } = state.userInfo
        let res = await getMenuList({ roleId })
        let { code, data } = res
        if (code === 0) {
          let { functionList: navList = [] } = data
          for (let item of navList) {
            let res = await getMenuList({ roleId, parentId: item.id })
            let { code, data } = res
            if (code === 0) {
              let { functionList } = data
              item.children = functionList
            }
          }
          commit('GET_NAVLIST', navList)
          resolve(navList)
        } else {
          reject(res)
        }
      })
    },
    /**
     * 获取左侧菜单列表
     */
    GET_MENULIST({ commit, state }, { id }) {
      return new Promise(async resolve => {
        let { navList } = state
        let { children } = navList.find(item => item.id * 1 === id * 1)
        let menuList = handleMenuListRoutes(children)
        commit('GET_MENULIST', { menuList, currentNav: `${id}` })
        let name = handleFirstRoute(menuList)
        resolve(name)
      })
    }
  }
}
